package algorithm.sort;

import java.util.Arrays;
import java.util.List;

/**
 * 二分法查找数据
 */
public class BinarySearch {

    public static int search(List<Integer> list , int searchKey){
        int startIndex = 0;
        int endIndex = list.size() - 1;
        int targetIndex;

        while (endIndex > startIndex){
            targetIndex = (startIndex + endIndex) / 2;
            if (list.get(targetIndex) == searchKey){
                return targetIndex;
            }
            else if ( list.get(targetIndex) < searchKey ){
                startIndex = targetIndex + 1;
            } else {
                endIndex = targetIndex - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14);
        int searchKey = 11;
        System.out.println(search(list , searchKey));
    }

}
